<template>
  <div class="app-container">
    <div class="filter-container clearfix">
      <el-button
        size="small"
        class="filter-item"
        style="margin-left: 10px;float:right"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate()"
      >添加分类</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      row-key="id"
      size="small"
      border
      fit
      highlight-current-row
      :indent="38"
      :tree-props="{children: 'proCatInfo', hasChildren: true}"
    >
      style="width: 100%;margin-top:1%"
      @selection-change="handleSelectionChange"
      >
      <el-table-column label="分类名称" class="fs" min-width="200px" align="left">
        <template slot-scope="scope">
          <div class="fs">
            <div class="fs" style="width:100px">
              <span>{{ scope.row.name }}</span>
            </div>
            <el-button
              class="fs"
              v-if="scope.row.isParent=='0'"
              size="mini"
              align="center"
              type="success"
              round
              @click="handleCreate(scope.row)"
            >新增下级</el-button>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="服务费" width="250px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.rate? scope.row.rate*100+'%':'' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="排序" width="250px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sortOrder }}</span>
        </template>
      </el-table-column>

      <el-table-column label="是否展示" width="250px" align="center">
        <template slot-scope="scope">
          <!-- <span>{{ scope.row.status }}</span> -->
          <div @click="clickStatus(scope.row)">
            <el-switch
              v-model="scope.row.status"
              active-value="0"
              inactive-value="1"
              @change="changeStatus(scope.row)"
            ></el-switch>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="450px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            size="medium"
            align="center"
            type="text"
            style="color:#0066FF"
            @click="handleUpdate(row)"
          >编辑</el-button>
          <span>|</span>
          <el-button
            size="medium"
            align="center"
            type="text"
            style="color:#0066FF"
            @click="handledelete(row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增一级分类 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      append-to-body
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="150px"
        style="width: 400px; margin-left:50px;"
        v-if="temp.isParent==='1'"
      >
        <el-form-item label="上级分类：">
          <el-input v-model="temp.parentName" disabled />
        </el-form-item>
        <el-form-item label="分类名称：">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="商品服务费：">
          <el-input v-model="temp.rate" style="float:left;width:200px" />
          <span style="float:left">%</span>
        </el-form-item>
        <el-form-item label="排序：">
          <el-input v-model="temp.sortOrder" />
        </el-form-item>
        <el-form-item label="展示状态：">
          <el-radio-group v-model="temp.status">
            <el-radio label="0">展示</el-radio>
            <el-radio label="1">不展示</el-radio>
          </el-radio-group>
          <!-- <el-select
            v-model="temp.status"
            @change="statusChange"
            size="small"
            placeholder="全部"
            class="filter-item"
            style="width: 130px"
          >
            <el-option
              v-for="item in calendarTypeOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>-->
        </el-form-item>
      </el-form>

      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="150px"
        style="width: 400px; margin-left:50px;"
        v-else
      >
        <el-form-item label="分类名称：">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="分类排序：">
          <el-input v-model="temp.sortOrder" />
        </el-form-item>
        <el-form-item label="展示状态：">
          <el-radio-group v-model="temp.status">
            <el-radio label="0">展示</el-radio>
            <el-radio label="1">不展示</el-radio>
          </el-radio-group>
          <!-- <el-select
            v-model="temp.status"
            @change="statusChange"
            size="small"
            placeholder="全部"
            class="filter-item"
            style="width: 130px"
          >
            <el-option
              v-for="item in calendarTypeOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>-->
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">返回</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  updateManu,
  manufacturerList,
  delManufacturer,
  createManufacturer,
  batchDel
} from "@/api/manufacturer"; // 异步请求 delLly

import {
  getAllCat,
  createProCat,
  deleteProCat
} from "@/api/purchase/proCatReq";
import { deleteFile, uploadFile } from "@/api/publicReq";
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // 分页插件

const calendarTypeOptions = [
  {
    key: "0",
    display_name: "展示"
  },
  {
    key: "1",
    display_name: "不展示"
  }
];
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  components: {
    Pagination
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger"
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    }
  },
  data() {
    return {
      dateValue: [],
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        phoneNumber: "",
        name: "",
        sort: "+id"
      },
      formImgUrl: "",
      deps: [],
      calendarTypeOptions,
      sortOptions: [
        {
          label: "ID Ascending",
          key: "+id"
        },
        {
          label: "ID Descending",
          key: "-id"
        }
      ],
      statusOptions: ["published", "draft", "deleted"],
      showReviewer: false,
      temp: {
        id: undefined,
        isParent: ""
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "修改",
        create: "添加"
      },
      rowId: "",
      dialogPvVisible: false,
      outerVisible: false,
      pvData: [],
      rules: {
        type: [
          {
            required: true,
            message: "type is required",
            trigger: "change"
          }
        ],
        timestamp: [
          {
            type: "date",
            required: true,
            message: "timestamp is required",
            trigger: "change"
          }
        ],
        title: [
          {
            required: true,
            message: "title is required",
            trigger: "blur"
          }
        ]
      },
      downloadLoading: false,
      liaUser: null,
      ids: [],
      select: null
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleSelectionChange(val) {
      val.forEach(item => {
        this.select = item.id;
      });
      this.ids.push(this.select);
    },

    // 改变展示状态
    clickStatus(temp) {
      // this.temp = temp;
      // console.log("1", this.temp);
    },
    changeStatus(e) {
      console.log(e);
      this.temp = e;
      console.log(that.temp);
      that.updataProCat();
    },

    // 获取list
    getList() {
      this.listLoading = true;
      var params = {
        // pageConvert: true,
        // pageNum: this.listQuery.pageNum,
        // pageSize: this.listQuery.pageSize,
        // name: this.listQuery.name,
        // phoneNumber:this.listQuery.phoneNumber
        // isParent: "0"
      };

      getAllCat(params).then(response => {
        this.list = response.data;
        console.log(response);
        this.total = response.recordsTotal;
        console.log(this.total);
        // Just to simulate the time of the request
        this.listLoading = false;
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: "操作Success",
        type: "success"
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        isParent: ""
      };
    },
    // 编辑弹窗
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      if (row.rate) {
        this.temp.rate = row.rate * 100;
      }
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    // 删除
    handleEnd(row) {
      this.$confirm("确定删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(() => {
          var rowId = row.id;
          timeoutScreenAds(rowId).then(res => {
            this.$message({
              type: "success",
              message: "成功!"
            });
            this.getList();
          });
          // })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.updataProCat();
        }
      });
    },

    // 修改数据
    updataProCat() {
      const tempData = Object.assign({}, this.temp);
      console.log(tempData);
      if (tempData.rate) {
        tempData.rate = Number(tempData.rate) / 100;
      }
      createProCat(tempData).then(() => {
        // for (const v of this.list) {
        //   if (v.id === this.temp.id) {
        //     const index = this.list.indexOf(v);
        //     this.list.splice(index, 1, this.temp);
        //     break;
        //   }
        // }
        this.dialogFormVisible = false;
        this.$notify({
          title: "成功",
          message: "修改成功",
          type: "success",
          duration: 2000
        });
        this.getList();
      });
    },

    // 新增弹窗
    handleCreate(row) {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      console.log(row);
      if (row) {
        // this.temp = Object.assign({}, row);
        this.temp.parentName = row.name;
        this.temp.parentId = row.id;
        this.temp.isParent = "1";
      } else {
        this.temp.isParent = "0";
      }

      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    // 上传图片
    addImg(data) {
      this.dialogLoading = true;
      const formData = new FormData();
      formData.append("file", data.file);
      uploadFile(formData).then(res => {
        console.log(res);
        this.dialogLoading = false;
        this.formImgUrl = res.data.filePath;
      });
    },

    // 添加数据
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          console.log(this.temp);
          var tempData = Object.assign({}, this.temp);
          if (tempData.rate) {
            tempData.rate = Number(tempData.rate) / 100;
          }

          createProCat(tempData).then(() => {
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000
            });
            this.getList();
          });
        }
      });
    },

    handledelete(row) {
      // this.rowId=row.broadPic
      this.$confirm("确定删除？ 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(() => {
          console.log(row);
          var formdata = {
            id: row.id
          };
          deleteProCat(formdata).then(result => {
            console.log(result);
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}`
        ? "ascending"
        : sort === `-${key}`
        ? "descending"
        : "";
    },

    statusChange(value) {
      this.temp.status = value;
    }
  }
};
</script>
<style scoped>
.clearfix {
  zoom: 1; /*IE6*/
}
.fs {
  display: inline-block;
}
.clearfix:after {
  content: ".";
  height: 0;
  clear: both;
  display: block;
  visibility: hidden;
}
</style>
